package com.habdqn.easybuy.dao.impl;

import com.habdqn.easybuy.dao.BaseDao;
import com.habdqn.easybuy.dao.OrderDao;
import com.habdqn.easybuy.entity.News;
import com.habdqn.easybuy.entity.Order;
import com.habdqn.easybuy.util.Page;
import com.habdqn.easybuy.util.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/12/3
 */
public class OrderDaoImpl extends BaseDao implements OrderDao {
    private String baseSelect = "SELECT id, user_id, create_time, cost, status FROM order";

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Order queryById(Integer id) {
        String sql = baseSelect + " WHERE id=?";
        List<Order> orders = getListByRS(executeQuery(sql,id));
        if (orders!=null && orders.size()>0){
            return orders.get(0);
        }
        return null;
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param condition 实例对象
     * @param page      分页对象
     * @return 集合
     */
    @Override
    public List<Order> queryAll(Order condition, Page<Order> page) {
        StringBuilder sql = new StringBuilder(baseSelect);
        List<Object> paramList = buildQueryConditions(condition, sql);
        buildPageQuery(sql,paramList,page);
        return getListByRS(executeQuery(sql.toString(), paramList.toArray()));
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param condition 实例对象
     * @return 对象列表
     */
    @Override
    public List<Order> queryAll(Order condition) {
        StringBuilder sql = new StringBuilder(baseSelect);
        List<Object> paramList = buildQueryConditions(condition, sql);
        return getListByRS(executeQuery(sql.toString(), paramList.toArray()));
    }

    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 影响行数
     */
    @Override
    public int insert(Order order) {
        String sql = "INSERT INTO `order`(user_id, create_time, cost, status) VALUES(?, ?, ?, ?)";
        Object[] params = {order.getUserId(),order.getCreateTime(),order.getCost(),order.getStatus()};
        return executeInsert(sql,params);
    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 影响行数
     */
    @Override
    public int update(Order order) {
        String sql = "UPDATE `order` SET user_id=?, create_time=?, cost=?, status=? WHERE id=?";
        Object[] params = {order.getUserId(),order.getCreateTime(),order.getCost(),order.getStatus(),order.getId()};
        return executeUpdate(sql,params);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 影响行数
     */
    @Override
    public int deleteById(Integer id) {
        String sql = "DELETE FROM `order` WHERE id=?";
        return executeUpdate(sql,id);
    }

    /**
     * 查询订单数量
     *
     * @param order
     * @return
     */
    @Override
    public int getTotal(Order order) {
        StringBuilder sql = new StringBuilder("SELECT COUNT(id) FROM `order`");
        List<Object> paramList = buildQueryConditions(order, sql);
        return (int) (long) uniqueResult(sql.toString(), paramList.toArray());

    }

    /**
     * 从结果集中提取对象集合
     *
     * @param rs 结果集
     * @return 订单集合
     */
    private List<Order> getListByRS(ResultSet rs) {
        List<Order> orders = null;
        try {
            if (rs != null) {
                orders = new ArrayList<>();
                while (rs.next()) {
                    Order order = new Order();
                    order.setId(rs.getInt("id"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setCreateTime(rs.getDate("create_time"));
                    order.setCost(rs.getDouble("cost"));
                    order.setStatus(rs.getInt("status"));
                    orders.add(order);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return orders;
    }

    /**
     * 组装新闻查询条件
     * @param order 新闻条件
     * @param sql 原始SQL
     * @return 参数集合
     */
    private List<Object> buildQueryConditions(Order order, StringBuilder sql) {
        List<Object> paramList = new ArrayList<>();
        if (order != null) {
            sql.append(" WHERE 1=1 ");
            if (order.getId() != null && order.getId() > 0) {
                sql.append(" AND id=? ");
                paramList.add(order.getId());
            }
            if (order.getUserId() != null && order.getUserId() > 0) {
                sql.append(" AND user_id=? ");
                paramList.add(order.getUserId());
            }
            // 一般不查询内容（新闻内容太多，一般需要全文索引或者搜索引擎）
            if (order.getCreateTime() != null) {
                sql.append(" AND create_time=? ");
                paramList.add(order.getCreateTime());
            }
            // 价格一般不查询
            if (order.getStatus() != null && order.getStatus() > 0) {
                sql.append(" AND status=? ");
                paramList.add(order.getStatus());
            }
        }
        return paramList;
    }
}
